/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package shmallarchitect.jpa.controllers;

import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.transaction.UserTransaction;
import shmallarchitect.jpa.controllers.exceptions.NonexistentEntityException;
import shmallarchitect.jpa.controllers.exceptions.RollbackFailureException;
import shmallarchitect.jpa.entities.Field;
import shmallarchitect.jpa.entities.Locum;

/**
 *
 * @author jaccus
 */
public class FieldJpaController {
    @Resource(mappedName="utx")
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "ShmallArchitectPU")
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Field field) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Locum locum = field.getLocum();
            if (locum != null) {
                locum = em.getReference(locum.getClass(), locum.getId());
                field.setLocum(locum);
            }
            em.persist(field);
            if (locum != null) {
                locum.getFields().add(field);
                locum = em.merge(locum);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Field field) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Field persistentField = em.find(Field.class, field.getId());
            Locum locumOld = persistentField.getLocum();
            Locum locumNew = field.getLocum();
            if (locumNew != null) {
                locumNew = em.getReference(locumNew.getClass(), locumNew.getId());
                field.setLocum(locumNew);
            }
            field = em.merge(field);
            if (locumOld != null && !locumOld.equals(locumNew)) {
                locumOld.getFields().remove(field);
                locumOld = em.merge(locumOld);
            }
            if (locumNew != null && !locumNew.equals(locumOld)) {
                locumNew.getFields().add(field);
                locumNew = em.merge(locumNew);
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = field.getId();
                if (findField(id) == null) {
                    throw new NonexistentEntityException("The field with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Field field;
            try {
                field = em.getReference(Field.class, id);
                field.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The field with id " + id + " no longer exists.", enfe);
            }
            Locum locum = field.getLocum();
            if (locum != null) {
                locum.getFields().remove(field);
                locum = em.merge(locum);
            }
            em.remove(field);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Field> findFieldEntities() {
        return findFieldEntities(true, -1, -1);
    }

    public List<Field> findFieldEntities(int maxResults, int firstResult) {
        return findFieldEntities(false, maxResults, firstResult);
    }

    private List<Field> findFieldEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Field as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Field findField(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Field.class, id);
        } finally {
            em.close();
        }
    }

    public int getFieldCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Field as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
